package me.sdevil507.supports.httplog;

import java.util.function.Predicate;

/**
 * 判断请求是否是json类型
 *
 * @author sdevil507
 * created on 2020/3/27
 */
public class JsonMediaTypeHelper {

    private JsonMediaTypeHelper() {
    }

    static final Predicate<String> JSON = contentType -> {
        if (contentType == null) {
            return false;
        }
        // implementation note: manually coded for improved performance
        String prefix = "application/";
        if (contentType.startsWith(prefix)) {
            int index = contentType.indexOf(';', 12);
            int length = 16;
            if (index != -1) {
                if (index > length) {
                    // application/some+json;charset=utf-8
                    return contentType.regionMatches(index - 5, "+json", 0, 5);
                }

                // application/json;charset=utf-8
                return contentType.regionMatches(index - 4, "json", 0, 4);
            } else {
                // application/json
                if (contentType.length() == length) {
                    return contentType.endsWith("json");
                }
                // application/some+json
                return contentType.endsWith("+json");
            }
        }
        return false;
    };
}
